//
//  XTXRegiViewController.m
//  xiaotianxin
//
//  Created by XYC on 2019/6/21.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXRegiViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "XTXSexButton.h"

@interface XTXRegiViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *iconHeadImageView;
@property (weak, nonatomic) IBOutlet XTXSexButton *manBtn;
@property (weak, nonatomic) IBOutlet XTXSexButton *womenBtn;
@property (weak, nonatomic) IBOutlet UITextField *nichenTextField;
@property (weak, nonatomic) IBOutlet UIButton *shengrianniu;
@property (weak, nonatomic) IBOutlet UITextField *shoujiTextField;
@property (weak, nonatomic) IBOutlet UITextField *yanzhengmaTextField;
@property (weak, nonatomic) IBOutlet UIView *shoujiyanzhengView;
@property (weak, nonatomic) IBOutlet UIButton *fasongyanzhengmaanniu;
@property (nonatomic, strong) UIImagePickerController *pickerController;
@property (nonatomic, strong) NSData *wjData;
@property (nonatomic, strong) MBProgressHUD *progreHud;
@property (nonatomic,strong) UIView *shengribeijingView;
@property (nonatomic,strong) UIDatePicker *picker;



@end

@implementation XTXRegiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self
    self.title = @"注册";
    [XTXGongView zanshifanhuianniubingqiezhixingfanhuianniudedianjishijianClick:@"后退按钮"];
    if (!self.useMode.photonum.length) {
        self.shoujiyanzhengView.hidden = NO;
    }
    
    [self chushihuajiemian];

    UITapGestureRecognizer *shoushiTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hedImgPickkShijian)];
    [self.iconHeadImageView addGestureRecognizer:shoushiTap];
    
    [self showBriViee];
    [self execTaskstartTime:0 intervalTime:0 repeats:NO async:NO];
}

-(void)execTaskstartTime:(NSTimeInterval)startTime intervalTime:(NSTimeInterval)intervalTime repeats:(BOOL)repeats async:(BOOL)async{
    
    if (startTime < 0 || (intervalTime <= 0 && repeats)) return ;
    
    // 创建队列
    dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
    
    // 创建定时器
    dispatch_source_t gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置时间
    /*
     dispatch_source_t  _Nonnull source: 定时器
     dispatch_time_t start: 开始的时间,dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC)，start多长时间后开始，NSEC_PER_SEC(纳秒)
     uint64_t interval：时间间隔
     uint64_t leeway: 误差，写0就好
     */
    uint64_t start = startTime;
    uint64_t interval = intervalTime;
    dispatch_source_set_timer(gcdTimer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC),  interval * NSEC_PER_SEC,0);
    
    // 加锁
    // 定时器的唯一标识
    // 存放到字典中
    
    // 解锁
    // 设置回调1
    // 启动定时器
    dispatch_resume(gcdTimer);
}
- (void)chushihuajiemian
{
    [self.iconHeadImageView sd_setImageWithURL:[NSURL URLWithString:self.useMode.headimage]];
    self.nichenTextField.text = self.useMode.nickname;
    [self.shengrianniu setTitle:self.useMode.birthday forState:UIControlStateNormal];
    if (self.useMode.sex.integerValue == 1) {
        self.manBtn.selected = YES;
        self.womenBtn.selected = NO;
    }
    else {
        self.manBtn.selected = NO;
        self.womenBtn.selected = YES;
        [self convert_dateType:[NSDate date] withDate_type:@"" withJudgeYear:NO];
    }
}
-(NSString *)convert_dateType:(NSDate *)date withDate_type:(NSString *)dateType withJudgeYear:(BOOL)judgeYear{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSString *newFormatter = @"";

    if ([dateType isEqualToString:@"1"]) {
        
        newFormatter = @" MM/dd";
        
    }else if ([dateType isEqualToString:@"2"]){
        
        newFormatter = @" MM/dd HH:mm";
        
    }else if ([dateType isEqualToString:@"3"]){
        
        newFormatter = @"-MM-dd HH:mm";
        
    }else{
        
        newFormatter = @"-MM-dd HH:mm";
    }
    
    NSString *otherNewFormatter;
    
    if (judgeYear) {
        
        NSString *dateTime1 = [formatter stringFromDate:date];
        NSString *dateTime2 = [formatter stringFromDate:[NSDate date]];
        
        if ([dateTime1 isEqualToString:dateTime2]) {
            
            otherNewFormatter = [NSString stringWithFormat:@"%@",newFormatter];
        }else{
            
            otherNewFormatter = [NSString stringWithFormat:@"YYYY%@",newFormatter];
        }
        
    }else{
        
        otherNewFormatter = [NSString stringWithFormat:@"YYYY%@",newFormatter];
    }
    
    [formatter setDateFormat:otherNewFormatter];
    NSString *dateString = [formatter stringFromDate:date];
    
    return dateString;
}
- (IBAction)manOrwomanxuanzeClick:(UIButton *)sender {
    
    if (sender.tag == 0) {
        self.manBtn.selected = YES;
        self.womenBtn.selected = NO;
        self.useMode.sex = @"1";
    }
    else {
        self.manBtn.selected = NO;
        self.womenBtn.selected = YES;
        self.useMode.sex = @"0";
    }
    if (!self.wjData.length) {
        if (sender.tag == 0) {
            [self getUseXinb:@"1"];
        }
        else {
            [self getUseXinb:@"0"];
            [self convert_dateType:[NSDate date] withDate_type:@"" withJudgeYear:NO];
        }
    }
}
-(NSString *)convert_Date:(NSDate *)date withDate_format:(NSString *)dateFormat withJudge_year:(BOOL)judgeYear{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (judgeYear) {
        
        NSString *dateTime1 = [formatter stringFromDate:date];
        NSString *dateTime2 = [formatter stringFromDate:[NSDate date]];
        
        if ([dateTime1 isEqualToString:dateTime2]) {
            
            [formatter setDateFormat:dateFormat];
            return [formatter stringFromDate:date];
            
        }else{
            
            [formatter setDateFormat:[NSString stringWithFormat:@"%@ %@",@"YYYY",dateFormat]];
            return [formatter stringFromDate:date];;
        }
    }
    
    [formatter setDateFormat:dateFormat];
    NSString *dateString = [formatter  stringFromDate:date];
    return dateString;
}

- (void)getUseXinb:(NSString *)xingbieString
{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"sex"] = xingbieString;
    
    WeakSelf
    [[NetworkTool sharedTools] requestMethod:POST URL:[NSString stringWithFormat:@"%@%@",Portaddress,huoqugengduoyonghuxinxidewangluojiekou] parameters:parameters finish:^(id responseObject, NSError *errpr) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            weakSelf.useMode.nickname = responseObject[@"nickname"];
            weakSelf.useMode.headimage = responseObject[@"headimage"];
            weakSelf.useMode.birthday = responseObject[@"birthday"];
            
            [weakSelf chushihuajiemian];

        });
    }];
    [self convertHourMinuteSecondTime:@"" withTimeType:@""];
}
-(NSString *)convertHourMinuteSecondTime:(NSString *)second withTimeType:(NSString *)timeType{
    
    NSInteger seconds = [second integerValue];
    // format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    // format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    
    if ([timeType isEqualToString:@"1"]) {
        // format of hour
        NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
        // format of time
        NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
        
        return format_time;
    }
    
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    return format_time;
}
- (IBAction)shengrixuanzeBtnClick:(UIButton *)sender {
    [self convertTimestamp:@"" withDateFormat:@""];
    [self briChangeChuxian];
}
-(NSString *)convertTimestamp:(NSString *)timestamp withDateFormat:(NSString *)dateFormat{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp longLongValue]];
    return [self convert_Date:date withDate_format:dateFormat withJudge_year:NO];
}
- (IBAction)quedingBtnClick:(UIButton *)sender {
    
    if (!self.nichenTextField.text.length) {
        [XTXGongView showTipMsg:@"昵称不能为空"];
        return;
    }
    if (self.nichenTextField.text.length > 10) {
        [XTXGongView showTipMsg:@"昵称不能大于10个字"];
        return;
    }
    if (!self.useMode.photonum.length) {
        if (self.shoujiTextField.text.length != 11) {
            [XTXGongView showTipMsg:@"请输入正确的手机号"];
            return;
        }
        if (!self.yanzhengmaTextField.text.length) {
            [XTXGongView showTipMsg:@"请输入验证码"];
            return;
        }
    }
    self.progreHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.progreHud hideAnimated:YES afterDelay:20.0];
    
    if (self.wjData.length) {
        [self touxiangshangchuangEventClick:self.wjData];
    }
    else {
        [self regiEveee];
    }
}
-(NSString *)convertJudgeYearTimestamp:(NSString *)timestamp withDateFormat:(NSString *)dateFormat{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp longLongValue]];
    return [self convert_Date:date withDate_format:dateFormat withJudge_year:YES];
}
- (void)touxiangshangchuangEventClick:(NSData *) fileData
{
    WeakSelf
    [XTXNetworking networkingUpUseLoginHeadImagedewangluoqingqiu:fileData completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] integerValue] == 1) {
            weakSelf.useMode.headimage = dict[@"info"][@"imageUrl"];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [XTXGongView showTipMsg:dict[@"msg"]];
            });
        }
        [weakSelf regiEveee];
        [weakSelf jk_time1TurnStringTimestamp:@""];
    }];
}
-(NSString *)jk_time1TurnStringTimestamp:(NSString *)timestamp
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]];
    NSTimeInterval  timeInterval = [date timeIntervalSinceNow];
    
    NSInteger seconds = round(timeInterval);
    
    if (seconds < 0) {
        return @"";
    }
    if (seconds < 60) {
        return @"刚刚";
    }else if (seconds < 3600) {
        return [NSString stringWithFormat:@"%ld分钟之前",seconds/60];
    }else if (seconds < 3600*24){
        return [NSString stringWithFormat:@"%ld小时之前",seconds/(3600)];
    }else if (seconds < (3600*24*30)){
        return [NSString stringWithFormat:@"%ld天之前",seconds/(3600*24)];
    }else if (seconds < (3600*24*30*12)){
        return [NSString stringWithFormat:@"%ld月之前",seconds/(3600*24*30)];
    }else{
        return [NSString stringWithFormat:@"%ld年之前",seconds/(3600*24*30*12)];
    }
}

-(void)regiEveee
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    parameters[@"username"] = self.useMode.photonum;
    parameters[@"phonecode"] = self.useMode.codeNum;
    parameters[@"sex"] = self.useMode.sex;
    parameters[@"headimage"] = self.useMode.headimage;
    parameters[@"nickname"] = self.nichenTextField.text;
    parameters[@"id"] = self.useMode.id;
    if ([self.useMode.birthday rangeOfString:@"/"].length) {
        self.useMode.birthday = [self.useMode.birthday stringByReplacingOccurrencesOfString:@"/" withString:@""];
    }
    parameters[@"birthday"] = self.useMode.birthday;
    parameters[@"fromwhere"] = fromwhere;
    
    NSString *tempUrl=shoujidengludewangluojiekou;

    WeakSelf
    [[NetworkTool sharedTools] requestMethod:POST URL:[NSString stringWithFormat:@"%@%@",Portaddress,tempUrl] parameters:parameters finish:^(id responseObject, NSError *errpr) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.progreHud hideAnimated:YES];
            [XTXGongView showTipMsg:responseObject[@"msg"]];
        });
        if ([responseObject[@"code"] isEqual:@"1"]) {
            
            XTXGongTool.share.useMode = [XTXUserModel yy_modelWithDictionary:responseObject[@"info"]];
            XTXTool.share.ConsumerModel = [ConsumerModel yy_modelWithDictionary:responseObject[@"info"]];
            XTXGongTool.share.useMode.momomo = @"0";
            [XTXGongTool baocungerenwangluqingiqushujuEventClick:XTXGongTool.share.useMode];
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"info"][@"defaultimage"] forKey:@"defaultimage"];
            [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"info"][@"single"] forKey:@"singleziduan"];
            [XTXGongView tianjiasuoyoudeTabdekongzhiqijiazaiEventClick];
            
        }else{
            [self jk_time2TurnStringTimestamp:@""];
        }
    }];
}
-(NSString *)jk_time2TurnStringTimestamp:(NSString *)timestamp{
    NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]];
    
    NSTimeInterval  timeInterval = [date1 timeIntervalSinceNow];
    timeInterval = -timeInterval;
    
    NSInteger time = round(timeInterval);
    
    long temp = 0;
    
    if (time < 60) {
        
        NSString *result = @"刚刚";
        
        return result;
    }
    else if((temp = timeInterval/60) <60){
        NSString *result = [NSString stringWithFormat:@"%ld分钟前",temp];
        return result;
    }
    
    else if((temp = temp/60) <24){
        NSString *result = [NSString stringWithFormat:@"%ld小时前",temp];
        return result;
    }
    
    else if((temp = temp/24) <30){
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        [dateFormatter setDateFormat:@"MM/dd hh:mm"];
        NSString *dateString = [dateFormatter stringFromDate:date1 ];
        
        
        return dateString;
    }
    
    else if((temp = temp/30) <12){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        [dateFormatter setDateFormat:@"MM/dd hh:mm"];
        NSString *dateString = [dateFormatter stringFromDate:date1 ];
        
        
        return dateString;
    }
    else{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        [dateFormatter setDateFormat:@"yyyy MM/dd hh:mm"];
        NSString *dateString = [dateFormatter stringFromDate:date1 ];
        
        
        return dateString;    }
    
    return  nil;
}

- (void)showBriViee
{
    _shengribeijingView = [[UIView alloc]initWithFrame:CGRectMake(0, pingmuGao, pingmuKuan, 250)];
    _shengribeijingView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_shengribeijingView];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *maxDate = [dateFormatter dateFromString:@"01-01-1998"];
    NSDate *minDate = [dateFormatter dateFromString:@"01-01-1950"];
    _picker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 40, pingmuKuan, 210)];
    self.picker.backgroundColor = rgbYanse(250,250,250);
    [self.picker setDate:[dateFormatter dateFromString:@"01-01-1990"] animated:YES];
    self.picker.datePickerMode = UIDatePickerModeDate;
    self.picker.minuteInterval = 10;
    self.picker.minimumDate = minDate;
    self.picker.maximumDate = maxDate;
    [self.picker setTintColor:[UIColor redColor]];
    [self.picker addTarget:self action:@selector(timXuazEvee:) forControlEvents:UIControlEventValueChanged];
    [_shengribeijingView addSubview:self.picker];
    UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(0, 40, pingmuKuan, 1)];
    lineview.backgroundColor = rgbYanse(231,231,231);
    [_shengribeijingView addSubview:lineview];
    UIButton * cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancel setTitle:@"取消" forState:(UIControlStateNormal)];
    cancel.titleLabel.font = [UIFont systemFontOfSize: 15];
    [cancel addTarget:self action:@selector(cancButtonClick)forControlEvents:UIControlEventTouchUpInside];
    [cancel setTitleColor:rgbYanse(105,105,105) forState:UIControlStateNormal];
    cancel.frame = CGRectMake(25, 0, 40, 40);
    [_shengribeijingView addSubview:cancel];
    UIButton * determine = [UIButton buttonWithType:UIButtonTypeCustom];
    [determine setTitle:@"确定" forState:(UIControlStateNormal)];
    determine.titleLabel.font = [UIFont systemFontOfSize: 15];
    [determine addTarget:self action:@selector(briChangeQueding)forControlEvents:UIControlEventTouchUpInside];
    [determine setTitleColor:rgbYanse(105,105,105) forState:UIControlStateNormal];
    determine.frame = CGRectMake(310, 0, 40, 40);
    [_shengribeijingView addSubview:determine];
    [self jk_laveTimeTurnString:0];
}
-(NSString *)jk_laveTimeTurnString:(NSInteger)seconds{
    
    if (seconds < 0) {
        return @"";
    }
    if (seconds < 60) {
        return @"马上";
    }else if (seconds < 3600) {
        return [NSString stringWithFormat:@"剩余%ld分钟",seconds/60];
    }else if (seconds < 3600*24){
        return [NSString stringWithFormat:@"剩余%ld小时",seconds/(3600)];
    }else {
        return [NSString stringWithFormat:@"剩余%ld天",seconds/(3600*24)];
    }
}

-(void)timXuazEvee:(id)sender{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    dateFormatter.dateFormat = @"yyyy/MM/dd";

    self.useMode.birthday = [dateFormatter stringFromDate:self.picker.date];
    [self jk_ageConstellationWithStamp:@""];
}
-(NSString *)jk_ageConstellationWithStamp:(NSString *)timestamp
{
    NSDate*detaildate = [NSDate date];
    //实例化一个NSDateFormatter对象
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate:detaildate];
    
    NSArray *strarr = [[self convertTimestamp:timestamp withDateFormat:@"yyyy-MM-dd"] componentsSeparatedByString:@"-"];
    if (strarr.count == 3) {
        return [NSString stringWithFormat:@"%ld岁",[currentDateStr integerValue] - [strarr[0] integerValue]];
    }
    else
    {
        return @"未知年龄";
    }
}

-(void)cancButtonClick
{
    [self jk_calculateConstellationWithStamp:@""];
    [self briChangeXiaoshi];
}
- (NSString *)jk_calculateConstellationWithStamp:(NSString *)timestamp{
    
    NSArray *strarr = [[self convertTimestamp:timestamp withDateFormat:@"yyyy-MM-dd"] componentsSeparatedByString:@"-"];
    
    if (strarr.count == 3) {
        return [self jk_calculateConstellationWithMonth:[strarr[1] integerValue] day:[strarr[2] integerValue]];
    }
    else
    {
        return @"未得到星座";
    }
}
-(void)briChangeQueding
{
    [self briChangeXiaoshi];
    [self.shengrianniu setTitle:self.useMode.birthday forState:UIControlStateNormal];

}
-(NSString *)jk_calculateConstellationWithMonth:(NSInteger)month day:(NSInteger)day{
    
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    
    if (month<1 || month>12 || day<1 || day>31){
        return @"错误日期格式!";
    }
    
    if(month==2 && day>29)
    {
        return @"错误日期格式!!";
    }else if(month==4 || month==6 || month==9 || month==11) {
        if (day>30) {
            return @"错误日期格式!!!";
        }
    }
    
    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(month*2-(day < [[astroFormat substringWithRange:NSMakeRange((month-1), 1)] intValue] - (-19))*2,2)]];
    
    return [NSString stringWithFormat:@"%@座",result];
}


- (void)briChangeChuxian
{

    WeakSelf
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.shengribeijingView.frame = CGRectMake(0, pingmuGao-250, pingmuKuan, 250);
    } completion:^(BOOL finished) {
        
    }];
    [self jk_numberOfSecondsTurnString:0];
}
-(NSString *)jk_numberOfSecondsTurnString:(NSInteger)seconds
{
    if (seconds <= 60) {
        return [NSString stringWithFormat:@"00:00:%02ld",seconds];
    }
    else if ((seconds>60) && (seconds<=3600))
    {
        return [NSString stringWithFormat:@"00:%02ld:%02ld",seconds/60,seconds%60];
    }
    else
    {
        return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",seconds/3600,seconds%3600/60,seconds%3600%60];
    }
}
-(void)briChangeXiaoshi
{
    WeakSelf
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.shengribeijingView.frame = CGRectMake(0, pingmuGao, pingmuKuan, 250);
    } completion:^(BOOL finished) {
        [self jsonConvertObject:@""];
    }];
}
-(id)jsonConvertObject:(nonnull NSString*)szValue {
    if (!szValue) {
        return nil;
    }
    NSError * error = nil;
    id obj = [NSJSONSerialization JSONObjectWithData:[szValue dataUsingEncoding:NSUTF8StringEncoding]
                                             options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        NSLog(@"%@",error.description);
        return nil;
    }
    return obj;
}

-(nullable NSString *)transform:(NSString *)chinese {
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    return [[pinyin uppercaseString] substringToIndex:1];
}

-(nonnull NSMutableAttributedString *)makeAttributedString:(nonnull NSString*)szOriginalString regionString:(nonnull NSString*)szRegionString regionStringColor:(nonnull UIColor*)color {
    if (szOriginalString == nil){
        szOriginalString = @"";
    }
    if (!szRegionString) {
        return nil;
    }
    NSMutableAttributedString *strAtt = [[NSMutableAttributedString alloc] initWithString:szOriginalString];
    [strAtt addAttribute:NSForegroundColorAttributeName value:color range:[szOriginalString rangeOfString:szRegionString]];
    return strAtt;
}
-(void)codTimeJIshi
{
    __block NSInteger codTimeJIshi = 59;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(codTimeJIshi <= 0){
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.fasongyanzhengmaanniu.titleLabel.text = @"重新发送";
                [self.fasongyanzhengmaanniu setTitle:@"重新发送" forState:UIControlStateNormal];
                self.fasongyanzhengmaanniu.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = codTimeJIshi % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.fasongyanzhengmaanniu.titleLabel.text = [NSString stringWithFormat:@"已发送(%.2dS)", seconds];
                [self.fasongyanzhengmaanniu setTitle:[NSString stringWithFormat:@"已发送(%.2dS)", seconds] forState:UIControlStateNormal];
                self.fasongyanzhengmaanniu.userInteractionEnabled = NO;
            });
            codTimeJIshi--;
            [self getContentSizeWithText:@"" font:[UIFont systemFontOfSize:12] size:CGSizeMake(0, 0)];
        }
    });
    dispatch_resume(_timer);
}
-(CGSize)getContentSizeWithText:(nonnull NSString *)text font:(nonnull UIFont *)font size:(CGSize)maxSize {
    CGSize size;
    NSDictionary * tdic  = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    size = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
    size.height += 2;//加两个像素,防止emoji被切掉.
    size.width = size.width >= maxSize.width ? maxSize.width : size.width;
    return size;
}


- (void)hedImgPickkShijian
{
    UIActionSheet *_sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                        delegate:self
                                               cancelButtonTitle:@"取消"
                                          destructiveButtonTitle:nil
                                               otherButtonTitles:@"拍照", @"相机胶卷", nil];
    [_sheet showInView:[UIApplication sharedApplication].keyWindow];
    [self checkMobileNumber:@""];
}
-(BOOL)checkMobileNumber:(nonnull NSString *)numberStr {
    if (numberStr.length <= 0)  return NO;
    NSString * regex = @"^1[34578]\\d{9}";
    NSPredicate  * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:numberStr];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    WeakSelf
    dispatch_after(0., dispatch_get_main_queue(), ^{
        if (buttonIndex == 0) {
            
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied){
                UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请你设置允许APP访问你的相机->设置->隐私->相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alart show]; return ;
            } else {
                weakSelf.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                
                weakSelf.pickerController.videoQuality = UIImagePickerControllerQualityTypeMedium;

                weakSelf.pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
                [weakSelf presentViewController:weakSelf.pickerController animated:YES completion:nil];
            }
            
        }
        else if(buttonIndex == 1) {
            [self checkVerifyCode:@"" withBits:0];
            weakSelf.pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:weakSelf.pickerController animated:YES completion:nil];
        }
    });
}
-(BOOL)checkVerifyCode:(nonnull NSString *)code withBits:(NSUInteger)bits {
    if (code.length <= 0) return NO;
    NSString * regex = [NSString stringWithFormat:@"^\\d{%lu}", (unsigned long)bits];
    NSPredicate  * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:code];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *ppp = [XTXGongTool tongguozhaoxiangjihuoquyizhangtupianEventClick:info[UIImagePickerControllerEditedImage]];
    self.wjData = UIImageJPEGRepresentation(ppp,0.2);
//    CGFloat wenjianChangdu = self.wjData.length/1024.0/1024.0;
    //NSLog(@"%fMB",wenjianChangdu);
    self.iconHeadImageView.image = info[UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self chackEmailAddress:@""];
    
}
-(BOOL)chackEmailAddress:(nonnull NSString *)address {
    if (address.length <= 0)  return NO;
    NSString * regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate  * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:address];
}
- (UIImagePickerController *)pickerController
{
    if (!_pickerController) {
        _pickerController = [[UIImagePickerController alloc] init];
        _pickerController.delegate = self;
        _pickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        _pickerController.allowsEditing = YES;

    }
    return _pickerController;
}

@end
